<?php
namespace App\Http\Controllers\Admin;

use App\AccessLog;
use App\AppChannel;
use App\AppChannelLog;
use App\BlackAccessLog;
use App\Http\Controllers\Controller;
use App\ReferLog;
use App\Services\PuvService;
use App\Services\UrlService;
use App\UidAppidRel;
use App\UserApp;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class ChannelController extends Controller
{
    /**
     * @Desc: 渠道列表
     * @Author: hank <maokeyang1031@gmail.com>
     * @param Request $request
     * @return \Illuminate\View\View
     */
    public function channelList(Request $request)
    {
        $wd = $request->input('wd');
        $appId = $request->input('app_id');

        $this->preFilter(new UidAppidRel(), $appId);

        $appChannelModel = new AppChannel();
        if (!empty($wd)) {
            $appChannelModel = $appChannelModel->where("name", "like", "%$wd%");
        }

        $list = $appChannelModel->where("app_id", $appId)->where("del_flag", 0)
            ->orderBy("id", "desc")->paginate(10);

        // 获取命中次数
        $service = new PuvService();

        $arr = [
            //"aqj.one",
            "cdsnbtc.pw",
            "mashang.pw",
            "youqian.pw"
        ];
        $host = $request->getHost();
        if ($host == "hgf.mobi") {
            $hostStr = $host;
        } else {
            $hostStr = "dww.tw";
        }

        foreach ($list as &$v) {
            $logCount = BlackAccessLog::where("channel_id", $v->id)->where("access_date", date("Y-m-d"))->count();
            $v->logCount = $logCount;

            // 获取今日pv 和uv 和访问ip数目
            $todayRes = $service->getPuvByChannelId($v->id, date("Y-m-d"), $appId);
            $v->pvCount = $todayRes['pv'];
            $v->uvCount = $todayRes['uv'];
            $v->ipCount = $todayRes['ip'];

            $yesDate = Carbon::yesterday()->toDateString();
            $getRes = $service->getPuvByChannelId($v->id, $yesDate, $appId);

            $v->lpvCount = $getRes['pv'];
            $v->luvCount = $getRes['uv'];
            $v->lipCount = $getRes['ip'];


            // 复制的链接随机
            $domainIndex = array_rand($arr);

            // $arr[$domainIndex]  暂时只用这一个dww.tw
            $v->url = "https://$hostStr"  . '/' . $v->short_url_word;
        }


        return view('admin.channel.index', ['list' => $list, 'wd' => $wd, 'appId' => $appId]);
    }


    /**
     * @Desc: 添加渠道
     * @Author: hank <maokeyang1031@gmail.com>
     * @param Request $request
     * @return \Illuminate\View\View
     */
    public function channelAddView(Request $request)
    {
        $appId = $request->get("app_id", 0);
        if (empty($appId)) {
            return abort(403, "请求参数错误");
        }
        return view('admin.channel.add', ['appId' => $appId]);
    }

    /**
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return mixed
     */
    public function channelAdd(Request $request)
    {
        $data   = $request->post();
        $channel = new AppChannel();

        // 短链接生成的关键字
        $shortUrlKeyWord = (new UrlService())->shortUrl();
//        // 判断下是否存在 如果存在重试一次
//        $res = AppChannel::where("short_url_word", $shortUrlKeyWord)->where("del_flag", 0)->first(["id"]);
//        if (empty($res)) {
//            $data["short_url_word"] = $shortUrlKeyWord;
//        }

        // 获取那个用户添加的
        $data["user_id"] = session("admin")->getUid();
        $data["short_url_word"] = $shortUrlKeyWord;

        $channel->fill($data)->save();
        return $this->json(200, '添加成功');
    }

    /**
     * @Desc: 修改渠道信息
     * @Author: hank <maokeyang1031@gmail.com>
     * @param Request $request
     * @param $id
     * @return \Illuminate\View\View
     */
    public function channelUpdateView(Request $request, $id)
    {
        return view('admin.channel.update', ['channel' => AppChannel::findOrFail($id)]);
    }

    public function channelUpdate(Request $request, $id)
    {
        $channel = AppChannel::findOrFail($id);

        if (!session('admin')->hasSuperRole()) {
            $uid = session("admin")->getUid();
            if ($channel->user_id != $uid) {
                return abort(403, "非法请求");
            }
        }

        // 备份之前的记录 每一次编辑都会做快照存储
        $bakeParams = [
            "channel_id" => $channel->id,
            "name" => $channel->name,
            "register_url" => $channel->name,
            "short_url_word" => $channel->short_url_word,
            "app_id" => $channel->app_id,
            "user_id" => $channel->user_id,
            "weixin_flag" => $channel->weixin_flag,
            "qq_flag" => $channel->qq_flag,
            "brown_flag" => $channel->brown_flag,
            "share_flag" => $channel->share_flag,
            "del_flag" => $channel->del_flag,
            "created_at" => $channel->created_at,
            "updated_at" => $channel->updated_at,
        ];
        AppChannelLog::insert($bakeParams);


        $data   = $request->post();

        if (empty($data["weixin_flag"])) {
            $data["weixin_flag"] = 0;
        }
        if (empty($data["brown_flag"])) {
            $data["brown_flag"] = 0;
        }
        if (empty($data["share_flag"])) {
            $data["share_flag"] = 0;
        }
        $channel->fill($data);

        $channel->save();
        return $this->json(200, '修改成功');
    }

    /**
     * @Desc: 删除渠道
     * @Author: hank <maokeyang1031@gmail.com>
     * @param $id
     * @return mixed
     */
    public function channelDel($id)
    {
        $referResult = AppChannel::where("id", $id)->first();
        if (empty($referResult)) {
            return abort("404", "参数错误");
        }
        if (!session('admin')->hasSuperRole()) {
            $uid = session("admin")->getUid();
            if ($uid != $referResult->user_id) {
                return abort(403, "非法请求");
            }
        }
        AppChannel::findOrFail($id)->update(["del_flag" => 1]);
        return $this->json(200, '删除成功');
    }

    /**
     * ajax 接口
     *
     */
    public function updateFlag()
    {
        $channelId = request()->get("channelId", 0);
        $type = request()->get("type", '');

        if (empty($channelId) || empty($type)) {
            return response()->json(["errcode" => 100]);
        }

        $state = request()->get("state", 0);
        $v = 0;
        if (!empty($state)) {
            $v = 1;
        }

        $updateParam[$type] = $v;
        AppChannel::where('id', $channelId)->update($updateParam);

        return response()->json(["errcode" => 0]);
    }

    /**
     * 渠道 puv统计
     * @param $id 渠道id
     * @return mixed
     */
    public function puv($id)
    {
        $service = new PuvService();
        $yesDate = Carbon::yesterday()->toDateString();
        $today = Carbon::now()->toDateString();

        $appId = AppChannel::where("id", $id)->value("app_id");

        $data['date0'] = $service->getPuvByChannelId($id, $yesDate, $appId);
        $data['date1'] = $service->getPuvByChannelId($id, $today, $appId);

        $data['appId'] = $appId;
        return view("admin.channel.puv", $data);
    }

    /**
     * 渠道 logSummary
     * @return mixed
     */
    public function logSummary()
    {
        $channelId = request()->get("channel_id", 0);
        $appRes = AppChannel::where("id", $channelId)->first(["app_id", "short_url_word"]);

        $referLogModel = ReferLog::select(DB::raw("count(1) as total, url, type, channel_id, channel_name, app_name"));

        $result = $referLogModel->where("channel_id", $channelId)->groupBy("url")->orderBy("total", "desc")->paginate(10);

        foreach ($result as &$item) {
            $item['channel_url'] = '';
            if (!empty($shortWord)) {
                $item['channel_url'] = "https://m.lhxq.top/t/" . ($appRes->short_url_word ?? '');
            }
        }

        $data["appId"] = $appRes->app_id ?? 0;
        $data["channelId"] = $channelId;
        $data["list"] = $result;
        return view("admin.channel.log_summary", $data);
    }

}
